package first.codeTop.byteDance;

/**
 * @ClassName Leetcode25
 * @description:
 * @author: 荣燊
 * @create: 2021-07-24 14:05
 **/
public class Leetcode25 {
    // k个一组翻转链表，困难题
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
    }

    public static ListNode reverseKGroup(ListNode head, int k) {
        // hair节点始终指向头结点
        ListNode hair = new ListNode(0);
        hair.next = head;
        // pre一直在反转链表的最后一个节点便于赋值
        ListNode pre = hair;

        // 先判断当前的剩余节点数是否大于k
        while (head != null) {
            ListNode tail = pre;
            for (int i=0; i<k; i++) {
                tail = tail.next;
                if (tail == null) {
                    return hair.next;
                }
            }
            // 开始反转
            ListNode next = tail.next; // 记录下一个还未反转的链表头
            ListNode[] reverse = reverse(head, tail);
            head = reverse[0];
            tail = reverse[1];
            // 反转后赋值操作
            // 1.先将节点接起来
            pre.next = head;
            tail.next = next;
            pre = tail;
            head = tail.next;
        }
        return hair.next;
    }

    // 翻转链表的一段，返回头尾节点
    public static ListNode[] reverse(ListNode head, ListNode tail) {
        ListNode pre = null;
        ListNode next = null;
        ListNode node = head;
        while (pre != tail) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        // 将反转后的头尾节点返回
        return new ListNode[]{pre, node};
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
